package com.lh.process.engine.config;

import com.alibaba.fastjson2.JSON;
import com.lh.process.engine.model.InvokeMethod;
import com.lh.process.engine.model.ProcessModel;
import com.lh.process.engine.model.ProcessNodeModel;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author: linghao
 * @since: 2022/10/19
 */
public abstract class XmlProcessParser implements ProcessParser {

    @Override
    public List<ProcessModel> parse() throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(XmlProcessParser.class.getClassLoader().getResource("process-demo.xml"));
        if(document == null){
            throw new IllegalArgumentException("流程配置文件解析加载失败");
        }
        //process标签
        List<Element> elements = document.getRootElement().elements();
        List<ProcessModel> list = new ArrayList<>();
        for(Element process : elements){
            ProcessModel processModel = new ProcessModel();
            processModel.setName(process.attributeValue("name"));
            //node标签
            List<Element> nodeElements = process.elements();
            for(Element node : nodeElements){
                ProcessNodeModel nodeModel = new ProcessNodeModel();
                nodeModel.setName(node.attributeValue("name"));
                nodeModel.setClassName(node.attributeValue("class"));
                String nextNode = node.attributeValue("next");
                if(null != nextNode){
                    nodeModel.setNextNode(nextNode);
                }
                String begin = node.attributeValue("begin");
                nodeModel.setBegin(Boolean.valueOf(begin));

                InvokeMethod method = node.attributeValue("invoke-method") == null ?
                        InvokeMethod.SYNC : InvokeMethod.valueOf(node.attributeValue("invoke-method").toUpperCase());
                nodeModel.setInvokeMethod(method);
                processModel.add(nodeModel);
            }
            list.add(processModel);
        }
        System.out.println(JSON.toJSONString(list));
        return list;
    }

}
